package com.powernode.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.shop.domain.Prod;
import com.powernode.shop.domain.ProdComm;
import com.powernode.shop.mapper.ProdCommMapper;
import com.powernode.shop.mapper.ProdMapper;
import com.powernode.shop.service.ProdCommService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author ZHAOZHENYU
* @since 2022/10/12
*/
@Service
public class ProdCommServiceImpl extends ServiceImpl<ProdCommMapper, ProdComm> implements ProdCommService{

    @Autowired
    private ProdCommMapper prodCommMapper;

    @Autowired
    private ProdMapper prodMapper;

    @Override
    public Page<ProdComm> selectProdComm(Page<ProdComm> page, ProdComm prodComm) {

        Page<ProdComm> prodCommPage = new Page<>(page.getCurrent(),page.getSize());
        List<Long> idList = null;
        if (StringUtils.hasText(prodComm.getProdName())){
            // 前端有模糊查询则查询 筛选商品
            List<Prod> prodList = prodMapper.selectList(new LambdaQueryWrapper<Prod>()
                    .like(Prod::getProdName, prodComm.getProdName()));
            if (CollectionUtils.isEmpty(prodList)) {
                // 如果为空
                prodCommPage.setTotal(0L);
                return prodCommPage;
            }
            // 查询商品
            idList = prodList.stream().map(Prod::getProdId).collect(Collectors.toList());
        }

        // 分页查询全部评论 不管有无模糊
        prodCommPage = prodCommMapper.selectPage(page, new LambdaQueryWrapper<ProdComm>()
                .eq(!ObjectUtils.isEmpty(prodComm.getStatus()), ProdComm::getStatus, prodComm.getStatus())
                .in(!CollectionUtils.isEmpty(idList), ProdComm::getProdId, idList)
                .orderByDesc(ProdComm::getRecTime)
        );
        // 获取评论集合
        List<ProdComm> prodCommList = prodCommPage.getRecords();
        if (!CollectionUtils.isEmpty(prodCommList)) {
            List<Long> prodIdList = prodCommList.stream().map(ProdComm::getProdId).collect(Collectors.toList());
            // 查出所有评论里面对应所有的商品
            List<Prod> prodList = prodMapper.selectBatchIds(prodIdList);

            // 查出的商品名称 重新给商品赋值
            prodCommList.forEach(prodComm1 -> {
                Prod prod1 = prodList.stream()
                        .filter(prod -> prod.getProdId().equals(prodComm1.getProdId()))
                        .collect(Collectors.toList())
                        .get(0);
                // 赋值
                prodComm1.setProdName(prod1.getProdName());
            });

        }
        return prodCommPage;
    }
}
